<template>
  <div style="width: 100vw;height: 100vh;display: flex;flex-direction: column;overflow: hidden;">
    <div style="height: 10vh; background-color: #f5f5f5; min-height: 60px; flex-shrink: 0;">
      <el-row :gutter="10">
        <el-col :span="1">
          <img src="../../../public/imgs/login/leaf.png" style="height: 40px; padding-top: 13px; padding-left: 16px;">
        </el-col>
        <el-col :span="15">
          <span style="font-size: 25px; color: #35984b; padding-left: 40px; line-height: 10vh;font-weight: bold;">垃圾分类管理项目后台</span>
        </el-col>
      </el-row>
    </div>

    <div style="display: flex; height: 90vh;">
      <!-- 左侧菜单栏 -->
      <div style="width: 228px">
        <el-menu
            background-color="#35984b"
            style="width: 100%; height: 100vh; border: none;"
            text-color="#fff"
            active-text-color="#fff"
            router
            :collapse-transition="true"
        >
          <el-menu-item index="/adminNotice">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><Promotion /></el-icon>
              <span class="left-menu-item">资讯管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminGarbage">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><DeleteFilled /></el-icon>
              <span class="left-menu-item">垃圾管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminUser">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><UserFilled /></el-icon>
              <span class="left-menu-item">用户管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/adminPut">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><CircleCheckFilled /></el-icon>
              <span class="left-menu-item">投放管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/admin">
            <template #title>
              <el-icon style="font-size: 24px; padding-left: 12px;"><Avatar /></el-icon>
              <span class="left-menu-item">个人中心</span>
            </template>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧顶部条与主体内容（可变区域）-->
      <div style="width: calc(100% - 228px)">
        <el-header style="height: 80px; background-color: #fff; padding-top: 22px;">
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" style="position:relative; ">
            <el-breadcrumb-item v-for="item in breadcrumb" style="font-size: 18px; font-weight: bold; margin-left: 10px; margin-top: 10px;">| {{ item }}</el-breadcrumb-item>
          </el-breadcrumb>
        </el-header>
        <!-- 右侧主体内容 -->
        <el-main style=" padding: 0; height: calc(100vh - 10vh - 100px); overflow-y: auto;">
          <div class="admin-profile-container" style="height: calc(100vh - 10vh - 100px)">
            <div class="admin-main">
              <!-- 侧边栏 -->
              <aside class="admin-sidebar">
                <div class="user-info-card">
                  <h3 class="user-name">{{ user.username }}</h3>
                  <p class="user-role">{{ user.role }}</p>
                  <p class="user-gender">性别：{{user.gender}}</p>
                  <p class="user-phone">电话号码：{{user.phone}}</p>
                </div>

                <el-menu
                    :default-active="activeTab"
                    class="admin-menu green-theme"
                    @select="handleMenuSelect"
                    text-color="#666"
                    active-text-color="#008800"
                >
                  <el-menu-item index="profile">
                    <el-icon><User /></el-icon>
                    <span>个人资料修改</span>
                  </el-menu-item>
                  <el-menu-item index="password">
                    <el-icon><Lock /></el-icon>
                    <span>修改密码</span>
                  </el-menu-item>
                </el-menu>
              </aside>

              <!-- 主内容区 -->
              <main class="profile-content">
                <!-- 个人资料 -->
                <div v-show="activeTab === 'profile'" class="profile-section">
                  <h2 class="section-title">个人信息</h2>
                  <el-form
                      ref="profileFormRef"
                      :model="user"
                      :rules="rules"
                      label-width="100px"
                      class="profile-form"
                  >
                    <el-form-item label="用户名" prop="username">
                      <el-input v-model="user.username" />
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                      <el-input v-model="user.phone" />
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                      <el-radio-group v-model="user.gender">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="角色">
                      <el-tag type="info">{{ user.role }}</el-tag>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="info" @click="resetProfile">重置</el-button>
                      <el-button type="success" @click="saveAdmin">保存修改</el-button>
                    </el-form-item>
                  </el-form>
                </div>

                <!-- 修改密码 -->
                <div v-show="activeTab === 'password'" class="password-section">
                  <h2 class="section-title">修改密码</h2>
                  <el-form
                      ref="passwordFormRef"
                      :model="passwordForm"
                      :rules="passwordRules"
                      label-width="100px"
                      class="password-form"
                  >
                    <el-form-item label="原密码" prop="oldPassword">
                      <el-input
                          v-model="passwordForm.oldPassword"
                          type="password"
                          show-password
                          placeholder="请输入原密码"
                      />
                    </el-form-item>

                    <el-form-item label="新密码" prop="newPassword">
                      <el-input
                          v-model="passwordForm.newPassword"
                          type="password"
                          show-password
                          placeholder="请输入新密码(6-20位字符)"
                      />
                    </el-form-item>

                    <el-form-item label="确认密码" prop="confirmPassword">
                      <el-input
                          v-model="passwordForm.confirmPassword"
                          type="password"
                          show-password
                          placeholder="请输入确认密码"
                      />
                    </el-form-item>

                    <el-form-item>
                      <el-button type="info" @click="resetPassword">重置</el-button>
                      <el-button type="success" @click="submitPassword">确认修改</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </main>
            </div>
          </div>
        </el-main>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  Message,
  Delete,
  User,
  Avatar,
  ArrowDown,
  SwitchButton,
  Promotion,
  DeleteFilled,
  UserFilled,
  CircleCheckFilled,
  Lock
} from '@element-plus/icons-vue'
import axios from "axios";
import qs from "qs";

// 获取当前用户信息
const getUser = () => {
  return JSON.parse(localStorage.getItem('user')) || {};
}

// 获取当前登录用户的信息
const user = ref(getUser());

const toAdmin = () => {
  router.push('/admin');
}

const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: false,
  }).then(() => {
    localStorage.removeItem('user');
    window.location.href = '/login';
    user.value = '';
  }).catch(() => {

  })
}

// 更新面包屑映射
let map = {
  '/adminNotice': ['资讯管理'],
  '/adminGarbage': ['垃圾管理'],
  '/admin': ['个人中心'],
  '/adminUser': ['用户管理'],
  '/adminPut': ['投放管理'],
}
const breadcrumb = ref([]);
const route = useRoute();
const router = useRouter();
onMounted(() => {
  updateBreadcrumb(route);
  // 加载用户信息
  loadUserInfo();
})

// 加载用户信息
const loadUserInfo = () => {
  if (user.value.id) {
    axios.get(`http://localhost:8080/v1/user/select?id=${user.value.id}`).then((response) => {
      if (response.data.code === 2000) {
        user.value = response.data.data[0];
      } else {
        ElMessage.error(response.data.msg);
      }
    }).catch(error => {
      ElMessage.error('获取用户信息失败');
      console.error(error);
    });
  }
}

// 定义更新面包屑导航值的方法
const updateBreadcrumb = (route) => {
  const path = route.path;
  breadcrumb.value = map[path] || [];
}
// 监听路由变化，更新面包屑
router.beforeEach((to, from, next) => {
  updateBreadcrumb(to);
  next();
})

// 当前激活的标签页
const activeTab = ref('profile')

// 表单验证规则
const rules = reactive({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ]
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = reactive({
  oldPassword: [
    {required: true, message: '请输入原密码', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请再次输入新密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 表单引用
const profileFormRef = ref(null)
const passwordFormRef = ref(null)

// 菜单选择处理
const handleMenuSelect = (index) => {
  activeTab.value = index
}

// 保存管理员信息
const saveAdmin = () => {
  profileFormRef.value.validate((valid) => {
    if (valid) {
      const data = qs.stringify({
        id: user.value.id,
        username: user.value.username,
        phone: user.value.phone,
        gender: user.value.gender
      });

      axios.post('http://localhost:8080/v1/user/save', data)
          .then((response) => {
            if (response.data.code === 2000) {
              ElMessage.success('保存成功!');
              // 更新本地存储的用户信息
              const updatedUser = {
                ...user.value,
                username: user.value.username,
                phone: user.value.phone,
                gender: user.value.gender
              };
              localStorage.setItem('user', JSON.stringify(updatedUser));
            } else {
              ElMessage.error(response.data.msg);
            }
          })
          .catch((error) => {
            ElMessage.error('保存失败');
            console.error(error);
          });
    } else {
      return false;
    }
  });
}

// 重置个人信息表单
const resetProfile = () => {
  loadUserInfo();
}

// 提交密码修改
const submitPassword = () => {
  passwordFormRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('确定要修改密码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = qs.stringify({
          id: user.value.id,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        });

        axios.post('http://localhost:8080/v1/user/changePassword', data)
            .then((response) => {
              if (response.data.code === 2000) {
                ElMessage.success('密码修改成功');
                passwordFormRef.value.resetFields();
              } else {
                ElMessage.error(response.data.msg);
              }
            })
            .catch((error) => {
              ElMessage.error('修改密码失败');
              console.error(error);
            });
      })
    } else {
      return false;
    }
  });
}

// 重置密码表单
const resetPassword = () => {
  passwordFormRef.value.resetFields();
}
</script>

<style scoped>
.left-menu-item {
  font-size: 18px;
  padding-left: 12px;
}

.left-menu-collapse-item {
  font-size: 17px;
  border: none;
  height: 40px;
}

/* 自定义滚动条样式 */
.el-main::-webkit-scrollbar {
  width: 8px;
}

.el-main::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

.el-main::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

.admin-profile-container {
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.header-left h1 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.admin-name {
  margin: 0 8px;
  font-weight: 500;
}

.admin-main {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.admin-sidebar {
  width: 260px;
  padding: 20px;
  background-color: #fff;
  box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05);
}

.user-info-card {
  text-align: center;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.user-name {
  margin: 50px 0 5px;
  font-size: 21px;
}

.user-role {
  margin: 10px 0 10px;
  color: #666;
  font-size: 14px;
}

.user-gender {
  margin: 0 0 10px;
  color: #666;
  font-size: 14px;
}

.user-phone {
  margin: 0 0 10px;
  color: #666;
  font-size: 14px;
}

.admin-menu {
  border-right: none;
}

.admin-menu.green-theme {
  border-right: none;
}

.admin-menu.green-theme .el-menu-item {
  transition: all 0.3s;
}

.admin-menu.green-theme .el-menu-item:hover {
  background-color: #f5faf5 !important;
}

.profile-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #fff;
  margin: 20px;
  border-radius: 4px;
}

.section-title {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.profile-form,
.password-form {
  max-width: 600px;
}

.password-tips {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

@media (max-width: 768px) {
  .admin-main {
    flex-direction: column;
  }

  .admin-sidebar {
    width: 100%;
  }

  .profile-content {
    margin: 10px;
    padding: 15px;
    min-height: auto;
  }
}

/* 输入框 */
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #008800 inset !important;
}

/* 单选框 */
:deep(.el-radio__input.is-checked .el-radio__inner) {
  border-color: #008800 !important;
  background-color: #008800 !important;
}

/* 复选框 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  border-color: #008800 !important;
  background-color: #008800 !important;
}

/* 下拉框 */
:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #008800 inset !important;
  border-color: #008800 !important;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #35984b;
  border-color: #35984b;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #35984b;
}
</style>